package cn.yr.controller.manage;

import cn.yr.common.constant.UserConstants;
import cn.yr.common.util.AjaxResult;
import cn.yr.domain.entity.SysMenu;
import cn.yr.domain.entity.SysUser;
import cn.yr.service.manage.ISysMenuService;
import cn.yr.service.manage.system.TokenService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


@RestController
@RequestMapping("/system/menu")
public class SysMenuController {
	@Resource
	private ISysMenuService menuService;

	@Resource
	private TokenService tokenService;

	/**
	 * 响应返回结果
	 *
	 * @param rows 影响行数
	 * @return 操作结果
	 */
	protected AjaxResult toAjax(int rows)
	{
		return rows > 0 ? AjaxResult.success() : AjaxResult.error();
	}

	//获取菜单列表
	@GetMapping("/list")
	public AjaxResult list(SysMenu menu) {
		///LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
		Long userId = 1L;
		List<SysMenu> menus = menuService.selectMenuList(menu);
		return AjaxResult.success(menus);
	}

	// 根据菜单编号获取详细信息


	@GetMapping(value = "/{menuId}")
	public AjaxResult getInfo(@PathVariable Long menuId) {
		return AjaxResult.success(menuService.selectMenuById(menuId));
	}

	//获取菜单下拉树列表


	@GetMapping("/treeselect")
	public AjaxResult treeselect(SysMenu menu) {   //Long userId = loginUser.getUser().getUserId();
		Long userId = 1L;
		List<SysMenu> menus = menuService.selectMenuList(menu);
		return AjaxResult.success(menuService.buildMenuTreeSelect(menus));
	}

	@GetMapping(value = "/roleMenuTreeselect/{roleId}")
	public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
		SysUser user = tokenService.getUser();
		List<SysMenu> menus = menuService.selectMenuList();
		AjaxResult ajax = AjaxResult.success();
		ajax.put("menus", menuService.buildMenuTreeSelect(menus));
		return ajax;
	}

//新增菜单
	@PostMapping
	public AjaxResult add(@Validated @RequestBody SysMenu menu) {
		if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
			return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
		}
		return toAjax(menuService.insertMenu(menu));
	}

	//修改菜单


	@PutMapping
	public AjaxResult edit(@Validated @RequestBody SysMenu menu) {
		if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
			return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
		}
		return toAjax(menuService.updateMenu(menu));
	}

	// 删除菜单


	@DeleteMapping("/{menuId}")
	public AjaxResult remove(@PathVariable("menuId") Long menuId) {
		if (menuService.hasChildByMenuId(menuId)) {
			return AjaxResult.error("存在子菜单,不允许删除");
		}
		return toAjax(menuService.deleteMenuById(menuId));
	}
}
